package com.zzl.alligator.framework.security.hanlder;

import cn.hutool.http.HttpStatus;
import com.zzl.alligator.common.constant.Constants;
import com.zzl.alligator.common.util.JsonUtils;
import com.zzl.alligator.common.util.ServletUtils;
import com.zzl.alligator.common.util.SpringUtils;
import com.zzl.alligator.framework.async.AsyncManager;
import com.zzl.alligator.framework.security.LoginUser;
import com.zzl.alligator.framework.security.service.TokenService;
import com.zzl.alligator.framework.support.web.vo.JsonResult;
import com.zzl.alligator.management.system.domain.SysLoginRecord;
import com.zzl.alligator.management.system.service.ISysLoginRecordService;
import com.zzl.alligator.management.system.service.impl.SysLoginRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.TimerTask;

/**
 * 登出成功处理
 *
 * @author zhouziliang
 * @since 2020/6/27
 */
@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Autowired
    private TokenService tokenService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
                                Authentication authentication)
            throws IOException, ServletException {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (loginUser != null) {
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            AsyncManager.me().execute(new TimerTask() {
                @Override
                public void run() {
                    ISysLoginRecordService recordService = SpringUtils.getBean(SysLoginRecordService.class);
                    recordService.insertSysLoginRecord(SysLoginRecord.buildLoginRecord(request, loginUser,
                            Constants.SUCCESS,
                            "退出成功"));
                }
            });
        }
        ServletUtils.renderString(response,
                JsonUtils.toFormatJsonString(JsonResult.error(HttpStatus.HTTP_OK, "退出成功")));

    }
}
